package com.rush.springbootinit.blackfilter;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class NacosListioner implements InitializingBean {

    @NacosInjected
    private ConfigService configService;

    @Value("${nacos.config.data-id}")
    private String dataId;

    @Value("${nacos.config.group}")
    private String group;
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("nacos监听器启动");
        String config = configService.getConfigAndSignListener(dataId, group, 10, new Listener() {
            //新建多线程监听
            final ThreadFactory threadFactory = new ThreadFactory(){
                private final AtomicInteger poolNumber = new AtomicInteger(1);
                @Override
                public Thread newThread(@NonNull Runnable r) {
                    Thread thread = new Thread(r);
                    thread.setName("nacos-listener" + poolNumber.getAndIncrement());
                    return thread;
                }
            };
            final ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);


            @Override
            public Executor getExecutor() {
                return executorService;
            }

            //监听后续黑名单的变化
            @Override
            public void receiveConfigInfo(String s) {
                log.info("监听到配置文件变化，重新加载黑名单:{}", s);
                BlackIpUtils.rebuildBlackList(s);
            }
        });
        //初始化黑名单
        BlackIpUtils.rebuildBlackList(config);
    }
}
